import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { User } from '../../schemas/users/user.schema'; // 导入用户模型

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const requiredRoles = this.reflector.get<string[]>('roles', context.getHandler());
    if (!requiredRoles) return true;

    const request = context.switchToHttp().getRequest();
    const user = request.user as User; // 强制类型转换为User类型
    console.log(user);

    // 如果用户未登录或角色信息不存在，则拒绝访问
    if (!user || !user.roles) return false;

    // 检查用户是否拥有任意一个所需的角色
    const hasRole = () => requiredRoles.some(role => user.roles.includes(role));
    return user && user.roles && hasRole();
  }
}